package gupao.concurrency.threadpool.futures;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.FutureTask;

public class FutureTaskSample {

    static ConcurrentHashMap<String, FutureTask<Connection>> CONNECTION_POOL = new ConcurrentHashMap<>();

    static Connection getOrCreateConnection(String key) throws Exception {
        FutureTask<Connection> connectionTask = CONNECTION_POOL.get(key);
        if(connectionTask != null){
            return connectionTask.get();
        }
        FutureTask<Connection> newTask = new FutureTask<>(()-> {
            return Connection.build();
        });
        connectionTask = CONNECTION_POOL.putIfAbsent(key, newTask);
        if(connectionTask == null){
            connectionTask = newTask;
            connectionTask.run();
        }
        return connectionTask.get();
    }

    static class Connection{

        public static Connection build(){
            return new Connection();
        }
    }
}
